package com.android.svmc.app.mobile.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Scanner;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.android.svmc.app.mobile.util.CommonDefine;

public class SDCardController implements CommonDefine {
	private Context context;

	public SDCardController(Context context) {
		super();
		this.context = context;
	}

	/**
	 * @param path
	 *            : create folder with path in SDcard.
	 * @return true if sucessfull
	 */
	public boolean creatNewFolder(String nameFolder) {

		File sentertainmentDir = new File(Environment.getExternalStorageDirectory()
				+ nameFolder);
		Boolean isSDPresent = android.os.Environment.getExternalStorageState()
				.equals(android.os.Environment.MEDIA_MOUNTED);

		if (isSDPresent) {
			if (sentertainmentDir.exists() == false) {
				boolean result = sentertainmentDir.mkdirs();
				if (result == false) {
					Log.i(TAG, "Create folder false");
					return false;
				}
				Log.i(TAG, "Create folder sucessfull");
			}
		} else {
			Log.i(TAG, "Sdcard not present");
			return false;
		}
	return true;
		
	}

	/**
	 * Read content from file with path in Sdcard
	 * 
	 * @param path
	 * @param typeRead : "/n": enter (Xuống dòng ) , "" : Không xuống dòng sau một line
	 * @return
	 */
	public String ReadFromSdCard(String path ,String typeRead) {
		String aBuffer = "";
		String extStorageDirectory = Environment
				.getExternalStorageDirectory().toString();
		try {
			File myFile = new File(extStorageDirectory+"/"+path);
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(new InputStreamReader(
					fIn));
			String aDataRow = "";

			while ((aDataRow = myReader.readLine()) != null) {
				aBuffer += aDataRow + typeRead;
				//aBuffer += aDataRow;
			}

			// txtData.setText(aBuffer);
			myReader.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return aBuffer;
	}

	/**
	 * Write text to file .txt in Sdcard
	 * 
	 * @param source
	 *            : String
	 * @param path
	 *            :
	 * @return : true if sucessfull
	 */
	public boolean writeToSdCard(String source, String path) {
		try {
			String extStorageDirectory = Environment
					.getExternalStorageDirectory().toString();
			/* kiểm tra trạng thái của sdcard đã được gắn vào chưa */
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				Toast.makeText(context, "Sdcard was not mounted !!", 1).show();
				return false;// chua gan the sdcard
			} else {
				File myFile = new File(extStorageDirectory + "/" + path);
				String oldText = "";
				/* neu file da ton tai thi ghi tiep vao */
				if (myFile.exists()) {
					oldText = ReadFromSdCard(extStorageDirectory + "/" + path,"/n");			
				} else
					myFile.createNewFile();// tao file moi
				FileOutputStream fOut = new FileOutputStream(myFile);
				OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
				myOutWriter.append(oldText);
				myOutWriter.append(source);
				myOutWriter.close();
				fOut.close();
				// Toast.makeText(context, "Done writing SD 'mysdfile.txt'",
				// Toast.LENGTH_SHORT).show();
				return true;
			}

		} catch (Exception e) {
			return false;
		}
	}
	/**
	 *  write one line in file txt to save constant 
	 * @param source
	 * @param path
	 * @return
	 */
	public boolean writeOneLineToSdcard (String source, String path){
		try {
			String extStorageDirectory = Environment
					.getExternalStorageDirectory().toString();
			/* kiểm tra trạng thái của sdcard đã được gắn vào chưa */
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				Toast.makeText(context, "Sdcard was not mounted !!", 1).show();
				return false;// chua gan the sdcard
			} else {
				File myFile = new File(extStorageDirectory + "/" + path);
				String oldText = "";
				/* neu file da ton tai thi ghi tiep vao */
				if (myFile.exists()) {
					oldText = ReadFromSdCard(extStorageDirectory + "/" + path,"/n");
					if(oldText.length() != 0){
						oldText ="";
					}
				} else
					myFile.createNewFile();// tao file moi
				FileOutputStream fOut = new FileOutputStream(myFile);
				OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
				myOutWriter.append(oldText);
				myOutWriter.append(source);
				myOutWriter.close();
				fOut.close();
				// Toast.makeText(context, "Done writing SD 'mysdfile.txt'",
				// Toast.LENGTH_SHORT).show();
				return true;
			}

		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * ghi file anh vao sdcard
	 * 
	 * @param pathImageSource
	 *            : đường dẫn của file ảnh nguồn
	 * @param path
	 *            : đường dẫn đích cần lưu file ảnh
	 * @param Format
	 *            : định dạng ảnh PNG? JPEG
	 * @return : trả true khi đã ghi thành công, false ngược lại
	 */
	public boolean writeImageToSdCard(String pathImageSource, String path,
			int Format) {

		try {
			Bitmap bmImage = BitmapFactory.decodeFile(pathImageSource);

			String extStorageDirectory = Environment
					.getExternalStorageDirectory().toString();
			/* kiểm tra trạng thái của sdcard đã được gắn vào chưa */
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				Toast.makeText(context, "Sdcard was not mounted !!", 1).show();
				return false;
			} else {
				File myImage = new File(extStorageDirectory + "/" + path);

				FileOutputStream out = new FileOutputStream(myImage);
				switch (Format) {
				case JPEG:
					bmImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
					break;

				default:
					bmImage.compress(Bitmap.CompressFormat.PNG, 80, out);
					break;
				}

				out.flush();
				out.close();
				return true;
			}
		} catch (Exception e) {
			// Toast.makeText(context, e.getMessage(), 1).show();
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * Read image form sdcard with path image.
	 * 
	 * @param path
	 *            : local image in sdcard
	 * @return
	 */
	public Bitmap readImageFromSdCard(String path) {

		Bitmap bmImage = null;
		/* kiem tra the nho duoc cam chua */
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(context, "Sdcard was not mounted !!", 1).show();
			return null;
		}

		/* kiem tra duong dan ton tai ko */
		File file = new File(path);
		if (!file.exists()) {
			Toast.makeText(context, path + " not exits", 1).show();
			return null;
		}

		/* decode bitmap tu file */
		try {
			bmImage = BitmapFactory.decodeFile(path);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return bmImage;

	}

	/**
	 * @param FileName
	 *            : tên file cần tạo
	 * @param arrInput
	 *            : list chuỗi cần ghi file theo kiểu wirteline
	 * @throws IOException
	 */
	public void writeInteralStorage(String FileName, ArrayList<String> arrInput)
			throws IOException {
		try {
			FileOutputStream fos = null;

			fos = context.openFileOutput(FileName, Context.MODE_PRIVATE);
			OutputStreamWriter myOutWriter = new OutputStreamWriter(fos);
			for (String content : arrInput)
				myOutWriter.write(content + "\n");

			myOutWriter.close();
			fos.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * @param FileName
	 *            :tên file cần đọc
	 * @return trả về một list các chuỗi từ file đầu vào, mỗi item của list là
	 *         một dòng từ file đầu vào.
	 */
	public ArrayList<String> readTextFromInternalStorage(String FileName) {
		ArrayList<String> arrString = new ArrayList<String>();
		// String result = "";
		try {
			FileInputStream fis = context.openFileInput(FileName);
			Scanner sc = new Scanner(fis);
			while (sc.hasNextLine()) {
				// result += sc.nextLine();
				arrString.add(sc.nextLine());
			}
		} catch (FileNotFoundException e) {
			Log.i("anhson", "error read file");
		}

		return arrString;
	}

}
